//
//  RiksTable.js
//  SugLisSystem
//  生成控件类
//  Created by Mr.Right on 2012-12-04.
//  Copyright 2012 Mr.Right. All rights reserved.
//  愿我们的梦永不落空❤~

var dB = require('untils/DB');
var pubFun = require('untils/PubFun');
var exeSQL = require('untils/ExeSQL');
var insuCore = require('corecenter/InsuCore');
var riskCheckCenter = require('suggest/RiskCheckCenter');
var riskInfoHandler = require('suggest/RiskInfoHandler');
var tGlobalInput = require('GlobalInput');
var universalRiskUI = require('suggest/UniversalRiskTable');

var indicator = require('untils/Indicator').create({
	msg : '校验规则中,请稍后...',
	inbkcolor : '#000'
});
//整体界面参数
var riskTableUI;
var TABLE_WIDTH = 580;
var TABLE_HEIGHT = 660;

// 控件类型
var CONTRL_TYPE_EDITTEXT = '00';
var CONTRL_TYPE_OPTION = '01';
var CONTRL_TYPE_UNVERSAL = '99';

//只读标记
var READ_ONLY = '1';

var riskInfo = {};
var riskScreenState = {};

//整体投保界面
var riskTableUI;
/**
 * 入口方法
 * @param contNo 建议书号
 * @param insuredNo 被保人号
 * @param mainPolNo 主险保单号
 * @param riskBaseItems 全部险种信息
 * @param mainRiskCode 主险代码
 * @param styleFlag 界面样式(暂无功能，可补充)
 * */
function RiskTable(contNo, mainPolNo, riskBaseItems, mainRiskCode, styleFlag) {
	//初始化一些险种的信息
	riskInfo.contNo = contNo;
	riskInfo.mainPolNo = mainPolNo;
	riskInfo.riskBaseItems = riskBaseItems;
	riskInfo.mainRiskCode = mainRiskCode;
	riskInfo.styleFlag = styleFlag;
	backDataByContNo(contNo);
	if (isCallBackMark(mainPolNo)) {
		Ti.API.warn('[RiksTable]修改状态：回显');
		// 回显的时候刷新附加险的下拉列表（针对与豁免附加险情况和根据主险情况来过滤各种下拉值）
		//TODO 刷新所有附加险下拉选项
	} else {
		Ti.API.warn('[RiksTable]修改状态：新增');
	}

}

/**
 * 备份数据
 * @param contNo 保单号
 * */
function backDataByContNo(contNo) {
	var rePolDB = new dB('LSPol');
	rePolDB['contno'] = contNo;
	riskInfo.backData = rePolDB.query();
}

/**
 * 还原数据
 * @param contNo 保单号
 * */
function recoverDataByContNo(contNo) {
	var rePolDB = new dB('LSPol');
	rePolDB['contno'] = contNo;
	rePolDB.remove();
	for (var i = 0; i < riskInfo.backData.length; i++) {
		var mPolDB = new dB('LSPol');
		mPolDB.setSchema(riskInfo.backData[i]);
		mPolDB.insert();
	}
}

/**
 * 判断为新增或回显
 * @param mainPolNo 主险号
 * @return boolean
 * */
function isCallBackMark(mainPolNo) {
	var rePolDB = new dB('LSPol');
	rePolDB['mainpolno'] = mainPolNo;
	var reslut = rePolDB.query();
	return reslut.length > 0;
}

///////////////////////////////界面生成/////////////////////////////////
/**
 * 生成RiskTableUI
 * */
RiskTable.prototype.initRiskTableUI = function() {
	//显示主险头部
	var mSection = Ti.UI.createTableViewSection({
		headerTitle : '主险'
	});
	//主险的所有信息组成Row
	var mainRiskBaseItem = riskInfo.riskBaseItems[riskInfo.mainRiskCode];
	//名称列
	mSection.add(createNameRow(mainRiskBaseItem));
	//属性列
	for (var i = 0; i < mainRiskBaseItem.screenSet.length; i++) {
		var tempRow = createPropertiesRow(mainRiskBaseItem.screenSet[i], mainRiskBaseItem, true);
		if (tempRow != null) {
			mSection.add(tempRow);
		}
	}
	//显示附加险头部
	var sSection = Ti.UI.createTableViewSection({
		headerTitle : '附加险'
	});

	//是否存在附加险
	var hasSubRisk = false;
	for (var tempRiskCode in riskInfo.riskBaseItems) {
		if (tempRiskCode != riskInfo.mainRiskCode) {
			hasSubRisk = true;
			var tempSubRiskBaseItems = riskInfo.riskBaseItems[tempRiskCode];
			sSection.add(createNameRow(tempSubRiskBaseItems));
			if (tempSubRiskBaseItems.modify) {
				for (var i = 0; i < tempSubRiskBaseItems.screenSet.length; i++) {
					var tempRow = createPropertiesRow(tempSubRiskBaseItems.screenSet[i], tempSubRiskBaseItems, true);
					if (tempRow != null) {
						sSection.add(tempRow);
					}
				}
			}
		}
	}

	riskTableUI = Ti.UI.createTableView({
		style : Ti.UI.iPhone.TableViewStyle.GROUPED,
		backgroundColor : 'transparent',
		width : TABLE_WIDTH,
		height : TABLE_HEIGHT,
		data : ( hasSubRisk ? [mSection, sSection] : [mSection])
	});

}

RiskTable.prototype.getRiskTable = function() {
	Ti.API.warn('已经输出投保界面');
	return riskTableUI;
};

/**
 * 获取所有险种的数据
 * 暂时不用
 * */
function getAllRiskDatas() {
	//先获取主险的数据
	var mSection = riskTableUI.data[0];
	for (var i = 0; i < mSection.rowCount; i++) {
		var mainRiskTempRow = mSection.rows[i];
		var ctrlProp = mainRiskTempRow.firstTag.toString().toLowerCase();
		if (ctrlProp != 'riskcode') {
			var tempChild = mainRiskTempRow.children[1];
			var tempTag = tempChild.firstTag;
			var tempValue = tempTag.split('/');
			if (tempValue.length > 1) {
				riskInfo.riskBaseItems[riskInfo.mainRiskCode]['riskData'][ctrlProp + 'flag'] = tempValue[1];
			}
			riskInfo.riskBaseItems[riskInfo.mainRiskCode]['riskData'][ctrlProp] = tempValue[0];
		}
	}

	//只有主险的情况
	if (riskTableUI.sectionCount == 1) {
		return;
	}
	//获取附加险数据
	var sSection = riskTableUI.data[1];
	var tempSubRiskCode = '';
	for (var i = 0; i < sSection.rowCount; i++) {
		var subRiskTempRow = sSection.rows[i];
		var ctrlProp = subRiskTempRow.firstTag.toString().toLowerCase();
		if (ctrlProp == 'riskcode') {
			tempSubRiskCode = subRiskTempRow.secordTag;
		} else {
			var tempChild = subRiskTempRow.children[1];
			var tempTag = tempChild.firstTag;
			var tempValue = tempTag.split('/');
			if (tempValue.length > 1) {
				riskInfo.riskBaseItems[tempSubRiskCode]['riskData'][ctrlProp + 'flag'] = tempValue[1];
			}
			riskInfo.riskBaseItems[tempSubRiskCode]['riskData'][ctrlProp] = tempValue[0];
		}

	}

}

/**
 * 刷新下拉列表
 * */
function ReflashPullDownOption(riskCode, ctrlProp, ctrlValue) {
	//	getAllRiskDatas();
	var riskScreenValidata = new dB('LMRiskScreenValidate');
	riskScreenValidata['riskcode'] = riskCode;
	riskScreenValidata['controlcode'] = ctrlProp;
	riskScreenValidata['controlvalue'] = ctrlValue;
	var riskScreenValidataSet = riskScreenValidata.query();
	for (var i = 0; i < riskScreenValidataSet.length; i++) {
		//functionType 为改变控件的方式。1->改变值域，2->改变显影
		var functionType = riskScreenValidataSet[i]['functiontype'];
		//改变控件
		if (functionType == '1') {
			var relaValueSQL = riskScreenValidataSet[i]['relavaluesql'];
			var relaControlCode = riskScreenValidataSet[i]['relacontrolcode'];
			changeRow(riskCode, relaControlCode, relaValueSQL);
		} else if (functionType == '2') {
			var relaDivShow = riskScreenValidataSet[i]['reladivshow'];
			var relaDivCode = riskScreenValidataSet[i]['reladivcode'];
			var riskScreenDB = new dB('LMRiskScreen');
			riskScreenDB['riskcode'] = riskCode;
			riskScreenDB['ctrltype'] = relaDivCode;
			var riskScreenSet = riskScreenDB.query();
			if (relaDivShow == '0') {
				hiddenRows(riskCode, riskScreenSet);
			} else {
				showRows(riskCode, riskScreenSet);
			}
		}

	}
}

/**
 * 试算保费保额
 * */
function calcuteData() {
	//删除备用数据
	var deleteSQL = "DELETE FROM LSPOL WHERE MAINPOLNO = '" + riskInfo.riskBaseItems[mainRiskCode].polNo + "'";
	exeSQL.execUpdateSQL(deleteSQL);
	insuCore.calcutePol(riskInfo.riskBaseItems[mainRiskCode]);
	//TODO 豁免险计算处理未完成
	var ExemptionRiskArr = [];
	for (var subRiskCode in riskInfo.riskBaseItems) {
		if (riskInfoHandler.isExemptionRisk(subRiskCode)) {
			ExemptionRiskArr.push(subRiskCode);
			continue;
		}
		if (subRiskCode != mainRiskCode && riskInfo.riskBaseItems[subRiskCode].enable) {
			insuCore.calcutePol(riskInfo.riskBaseItems[subRiskCode]);
		}
	}
	for (var i = 0; i < ExemptionRiskArr.length; i++) {
		var exemptionRiskCode = ExemptionRiskArr[i];
		if (exemptionRiskCode != mainRiskCode && riskInfo.riskBaseItems[exemptionRiskCode].enable) {
			insuCore.calcutePol(riskInfo.riskBaseItems[exemptionRiskCode]);
		}
	}
	showCash();
}

/**
 * 回显保费保额
 * */
function showCash() {
	var mSection = riskTableUI.data[0];
	var tempRiskCode = riskInfo.mainRiskCode;
	for (var i = 0; i < mSection.rowCount; i++) {
		if (mSection.rows[i].controlType == 'TYPE1') {
			var ctrlType = mSection.rows[i].firstTag.toLowerCase();
			mSection.rows[i].children[1].setText(riskInfo.riskBaseItems[tempRiskCode].riskData[ctrlType]);
			mSection.rows[i].children[1].firstTag = riskInfo.riskBaseItems[tempRiskCode].riskData[ctrlType];
		}
	}

	if (riskTableUI.data.length == 1) {
		return;
	}

	var sSection = riskTableUI.data[1];
	for (var i = 0; i < sSection.rowCount; i++) {
		if (sSection.rows[i].firstTag == 'RiskCode') {
			tempRiskCode = sSection.rows[i].secordTag;
		}
		if (sSection.rows[i].controlType == 'TYPE1') {
			var ctrlType = sSection.rows[i].firstTag.toLowerCase();
			sSection.rows[i].children[1].setText(riskInfo.riskBaseItems[tempRiskCode].riskData[ctrlType]);
			sSection.rows[i].children[1].firstTag = riskInfo.riskBaseItems[tempRiskCode].riskData[ctrlType];
		}
	}

}

/**
 * 整个险种之间中间的规则校验
 * @param errorCallBack 存在错误回调(参数：错误列表)
 * @param toolTipCallBack 存在温馨提示回调(参数：温馨提示列表)
 * @param succedCallBack 校验通过回调(无参数)
 * */
RiskTable.prototype.checkRule = function(errorCallBack, toolTipCallBack, succedCallBack) {
	indicator.show();
	var reslut = riskCheckCenter.checkForOnePol(riskInfo.mainPolNo, 'FINAL');
	indicator.hide();
	if (reslut.errorSet.length > 0) {
		errorCallBack(reslut.errorSet);
		return;
	}
	if (reslut.toolTipSet.length > 0) {
		toolTipCallBack(reslut.toolTipSet);
		return;
	}
	succedCallBack();
}

module.exports = RiskTable;

/////////////////////////创建单条Row的基础方法/////////////////////////////////////
//背景颜色
var COLOR_NAME = '#FFFFFF';
var COLOR_PROP = '#FDF8E2';
//控件大小
var COMMON_HEIGHT = 42;
var COMMON_WIDTH = 580;
//字体大小
var FONT_SIZE = 16;
//基础控件位置
var WIDGET_TOP = 12;
//第一控件位置
var FIRST_WIDGET_LEFT = 17;
var FIRST_WIDGET_WIDTH = 370;
//第二控件位置
var SECORND_WIDGET_RIGHT = 43;
var SECORND_WIDGET_WIDTH = 200;

/**
 * 生成名称控件
 * @param Data 生成控件的参数
 *
 * */
function createNameRow(baseItem) {
	//整体控件列
	var riskNameRow = Ti.UI.createTableViewRow({
		backgroundColor : COLOR_NAME,
		height : COMMON_HEIGHT,
		width : COMMON_WIDTH,
		selectionStyle : Titanium.UI.iPhone.TableViewCellSelectionStyle.NONE,
	});
	riskNameRow.controlType = 'TYPE0';
	// 设定列额外属性增加
	riskNameRow.firstTag = 'RiskCode';
	riskNameRow.secordTag = baseItem.riskCode;
	//初始化控件的显隐状态
	riskScreenState[baseItem.riskCode] = {};
	//名称控件
	var riskNameLabel = Ti.UI.createLabel({
		text : '[' + baseItem.riskCode + ']' + baseItem.riskName,
		textAlign : 'left',
		font : {
			fontSize : FONT_SIZE,
			fontWeight : 'bold'
		},
		height : 'auto',
		width : FIRST_WIDGET_WIDTH,
		left : FIRST_WIDGET_LEFT,
		top : WIDGET_TOP
	});
	riskNameRow.add(riskNameLabel);

	//可选择框
	var riskSwitch = Ti.UI.createSwitch({
		// enabled : baseItem.deleteable,
		value : baseItem.modify,
		right : 10,
		top : 10,
		width : 40,
		height : 40,
	});

	//对部分险种进行处理
	//主险的情况下隐藏，默认为true
	if (baseItem.subRiskFlag == 'M') {
		riskSwitch.value = true;
		riskSwitch.visible = false;
	}

	//判断是否为组合险
	var reLMRiskRelaDB = new dB('LMRiskRela');
	reLMRiskRelaDB['riskcode'] = riskInfo.mainRiskCode;
	reLMRiskRelaDB['relariskcode'] = baseItem.riskCode;
	reLMRiskRelaDB['relacode'] = '02';
	reLMRiskRelaDB['salechnl'] = tGlobalInput.chanlesign;
	var reLMRiskRelaSet = reLMRiskRelaDB.query();
	var comboMark = false;
	for (var i = 0; i < reLMRiskRelaSet.length; i++) {
		if (reLMRiskRelaSet[i]['managecomgrp'] == '000000') {
			comboMark = true;
			break;
		}
	}
	//组合险默认为true，且不可修改
	if (comboMark) {
		riskSwitch.value = true;
		riskSwitch.enabled = false;
		//计算标记设定
		riskInfo.riskBaseItems[baseItem.riskCode].enable = true;
	}

	riskSwitch.addEventListener('change', function(e) {
		if (e.source.value) {
			Ti.API.warn('[RiksTable]打开险种:' + baseItem.riskCode);
			showRows(baseItem.riskCode, baseItem.screenSet);
		} else {
			Ti.API.warn('[RiksTable]关闭险种:' + baseItem.riskCode);
			hiddenAllRows(baseItem.riskCode);
		}
		baseItem.enable = e.source.value;
		calcuteData();
	});

	riskNameRow.add(riskSwitch);

	return riskNameRow;
}

/**
 * 生成单条控件
 * @param Data 生成控件的参数
 *
 * */
function createPropertiesRow(riskScreenData, riskBaseItem, isVisiable) {
	//增加判断 是否需要显示该列
	var LMRiskScreenValidata = new dB('LMRISKSCREENVALIDATE');
	LMRiskScreenValidata['riskcode'] = riskBaseItem.riskCode;
	LMRiskScreenValidata['functiontype'] = '2';
	LMRiskScreenValidata['reladivcode'] = riskScreenData.ctrlcode;
	LMRiskScreenValidata['reladivshow'] = '0'
	var LMRiskScreenValidataSet = LMRiskScreenValidata.query();
	for (var i = 0; i < LMRiskScreenValidataSet.length; i++) {
		var tempLMRiskScreenValidataSchema = LMRiskScreenValidataSet[i];
		var controlCode = tempLMRiskScreenValidataSchema['controlcode'].toLowerCase();
		if (riskBaseItem.riskData[controlCode] == tempLMRiskScreenValidataSchema['controlvalue']) {
			isVisiable = false;
			break;
		}
	}

	if (!isVisiable) {
		return null;
	}

	//整体控件列
	var propertiesRow = Ti.UI.createTableViewRow({
		backgroundColor : COLOR_PROP,
		height : COMMON_HEIGHT,
		width : COMMON_WIDTH,
		selectionStyle : Titanium.UI.iPhone.TableViewCellSelectionStyle.NONE,
	});
	//列额外属性增加
	//用于显示，隐藏
	propertiesRow.index = riskScreenData['ctrlindex'];
	riskScreenState[riskScreenData['riskcode']][riskScreenData['ctrltype']] = true;
	//firstTag->控件标记（类似与PayIntv）
	//secordTag->控件类型（下拉，输入or输出）
	//thirdTag->只读属性（可写为''）
	propertiesRow.firstTag = riskScreenData['ctrltype'];
	var method = riskScreenData['ctrlproperty'];
	propertiesRow.secordTag = method;
	var readOnly = pubFun.isNull(riskScreenData['ctrlproperty2']) ? '' : riskScreenData['ctrlproperty2'];
	propertiesRow.thirdTag = readOnly;

	//名称控件
	var propertiesMarkLabel = Ti.UI.createLabel({
		text : riskScreenData['ctrlname'],
		font : {
			fontSize : FONT_SIZE,
			fontWeight : 'bold'
		},
		height : 'auto',
		width : 'auto',
		top : WIDGET_TOP,
		left : FIRST_WIDGET_LEFT
	});

	propertiesRow.add(propertiesMarkLabel);

	//根据类型来判读生成何种界面

	if (method == CONTRL_TYPE_EDITTEXT && readOnly == READ_ONLY) {
		//情况1，生成只读的展示信息列
		propertiesRow.controlType = 'TYPE1';
		var resultLabel = Ti.UI.createLabel({
			font : {
				fontSize : 16,
				fontWeight : 'bold'
			},
			right : SECORND_WIDGET_RIGHT,
			top : 7,
			width : 400,
			height : 30,
			textAlign : 'right'
		});
		resultLabel.firstTag = '';
		resultLabel.secordTag = '';
		resultLabel.thirdTag = '';
		propertiesRow.add(resultLabel);

		var unitLabel = Ti.UI.createLabel({
			text : '元',
			font : {
				fontSize : FONT_SIZE,
				fontWeight : 'bold'
			},
			textAlign : 'right',
			right : 18,
			top : 12,
		});

		if (riskBaseItem.riskData[riskScreenData['ctrltype'].toLowerCase()] != null) {
			resultLabel.setText(riskBaseItem.riskData[riskScreenData['ctrltype'].toLowerCase()]);
		}

		propertiesRow.add(unitLabel);

	} else if (method == CONTRL_TYPE_EDITTEXT) {
		//情况2，生成输入列
		propertiesRow.controlType = 'TYPE2';
		var cashLabel = Ti.UI.createTextField({
			hintText : '请输入金额',
			textAlign : 'right',
			font : {
				fontSize : FONT_SIZE,
				fontWeight : 'bold'
			},
			right : SECORND_WIDGET_RIGHT,
			top : 7,
			width : SECORND_WIDGET_WIDTH,
			height : 30,
			borderStyle : Ti.UI.INPUT_BORDERSTYLE_NONE,
			returnKeyType : Titanium.UI.RETURNKEY_DEFAULT,
			keyboardType : Titanium.UI.KEYBOARD_NUMBER_PAD
		});

		cashLabel.firstTag = '';
		cashLabel.secordTag = '';
		cashLabel.thirdTag = '';

		if (riskBaseItem.riskData[riskScreenData['ctrltype'].toLowerCase()] != null) {
			cashLabel.value = riskBaseItem.riskData[riskScreenData['ctrltype'].toLowerCase()];
		}

		propertiesRow.add(cashLabel);
		cashLabel.addEventListener('change', function(e) {
			//控制只能输入10位数字
			var val = e.source.value;
			val = val.replace(/[^0-9]/gi, '')
			if (val.indexOf('0') == 0) {
				val = val.substring(1);
			}
			e.source.value = val.slice(0, 10);
			riskBaseItem.riskData[riskScreenData['ctrltype'].toLowerCase()] = e.source.value;
			if (riskScreenData['ctrltype'].toLowerCase() == 'amnt') {
				riskBaseItem.riskData['get'] = e.source.value;
			}
			if (cashLabel.cancelCalcute) {
				clearTimeout(cashLabel.cancelCalcute);
			}
			cashLabel.cancelCalcute = setTimeout(calcuteData, 200);
		})
		var unitLabel = Ti.UI.createLabel({
			text : '元',
			font : {
				fontSize : FONT_SIZE,
				fontWeight : 'bold'
			},
			textAlign : 'right',
			right : 18,
			top : 12,
		});
		propertiesRow.add(unitLabel);

	} else if (method == CONTRL_TYPE_OPTION) {
		//情况3，生成下拉列
		propertiesRow.controlType = 'TYPE3';
		var resultLabel = Ti.UI.createLabel({
			font : {
				fontSize : FONT_SIZE,
				fontWeight : 'bold'
			},
			left : 90,
			top : 5,
			width : 380,
			height : 30,
			textAlign : 'right'
		});
		propertiesRow.add(resultLabel);
		//放置数据
		//fisrtTag->数据
		//secorndTag->默认sql
		//thirdTag->可选择列表
		resultLabel.firstTag = '';
		resultLabel.secorndTag = riskScreenData['defaultsql'];
		resultLabel.thirdTag = riskInfoHandler.CalSQLValue(riskScreenData['defaultsql'], riskBaseItem);
		var pullDownView = Ti.UI.createImageView({
			image : 'images/pull_down.png',
			height : 33,
			width : 37,
			right : 10,
		});
		pullDownView.addEventListener('click', function(e) {
			showOption(riskScreenData, resultLabel, e.source);
		})
		var tempvalue = '';
		if (riskBaseItem.riskData[riskScreenData['ctrltype'].toLowerCase()] != null) {
			tempvalue = riskBaseItem.riskData[riskScreenData['ctrltype'].toLowerCase()];
		}
		if (riskBaseItem.riskData[riskScreenData['ctrltype'].toLowerCase() + 'flag'] != null) {
			tempvalue += ('/' + riskBaseItem.riskData[riskScreenData['ctrltype'].toLowerCase() + 'flag']);
		}

		if (tempvalue.toString() != '') {
			resultLabel.setText(riskInfoHandler.FindTitleByValue(resultLabel.thirdTag, tempvalue));
			resultLabel.value = tempvalue;
			resultLabel.firstTag = tempvalue;
		}
		propertiesRow.add(pullDownView);
	} else if (method == CONTRL_TYPE_UNVERSAL) {
		var standByFlag3 = riskBaseItem.riskData['standbyflag3'];
		if (standByFlag3 == null) {
			standByFlag3 = Ti.Platform.createUUID();
			riskBaseItem.riskData['standbyflag3'] = standByFlag3;
		}

		var infoListView = Ti.UI.createImageView({
			image : 'images/info_list.png',
			height : 33,
			width : 37,
			right : 50,
		});

		infoListView.addEventListener('click', function(e) {
			//TODO 弹出详细列表
			showUniData(riskBaseItem.riskCode, standByFlag3, e.source);
		});

		propertiesRow.add(infoListView);

		var detailSetView = Ti.UI.createImageView({
			image : 'images/detail_set.png',
			height : 33,
			width : 37,
			right : 10,
		});
		detailSetView.addEventListener('click', function(e) {
			//TODO 添加万能险数据
			var mUniversalRiskUI = new universalRiskUI(riskBaseItem.riskCode, standByFlag3);
			mUniversalRiskUI.create();
			mUniversalRiskUI.open();
		})
		propertiesRow.add(detailSetView);
	}
	return propertiesRow;
}

function showOption(riskScreenData, wedget, showWedget) {
	var popover = Ti.UI.iPad.createPopover({
		width : 300,
		height : 180,
		title : riskScreenData['ctrlname'],
		barColor : '#ffffff'
	});

	var tableView = Ti.UI.createTableView({
		data : wedget.thirdTag,
		top : 0,
		height : 180
	});

	tableView.addEventListener('click', function(e) {
		wedget.setText(e.source.title);
		wedget.value = e.source.value;
		wedget.firstTag = e.source.value;
		popover.hide({
			animated : true
		});
		var reslutValue = e.source.value;
		// 刷新下拉列表
		var riskCode = riskScreenData['riskcode'];
		var ctrlType = riskScreenData['ctrltype'];
		var reslutArray = reslutValue.split('/');
		if (reslutArray.length > 1) {
			riskInfo.riskBaseItems[riskCode].riskData[ctrlType.toLowerCase() + 'flag'] = reslutArray[1];
		}

		riskInfo.riskBaseItems[riskCode].riskData[ctrlType.toLowerCase()] = reslutArray[0];
		ReflashPullDownOption(riskCode, ctrlType, reslutValue);
		calcuteData();
	})
	popover.add(tableView);

	popover.show({
		view : showWedget,
		animated : true,
	});
}

/**
 * 控制列的显示,IOS中只能insert
 * 只适用于主险和附加险，万能险需要另外处理！！！！
 * @param riskCode 险种代码
 * @param riskScreenDatas 需要插入的列的参数 Array类型
 * */
function showRows(riskCode, riskScreenDatas) {
	//计算名称列所在行在tableView中的索引
	//主险必为0,附加险需要计算
	var riskNameRowIndex = 0;
	if (riskCode != riskInfo.mainRiskCode) {
		var mSection = riskTableUI.data[0];
		var sSection = riskTableUI.data[1];
		for (var i = 0; i < sSection.rowCount; i++) {
			if (sSection.rows[i].secordTag == riskCode) {
				riskNameRowIndex = mSection.rowCount + i;
				break;
			}
		}
	}

	for (var i = 0; i < riskScreenDatas.length; i++) {
		if (riskScreenState[riskCode][riskScreenDatas[i]['ctrltype']]) {
			continue;
		}
		var ctrlIndex = riskScreenDatas[i]['ctrlindex'];
		var sql = "SELECT COUNT(1) FROM LMRISKSCREEN WHERE CTRLINDEX < " + ctrlIndex + " AND RISKCODE = '" + riskCode + "'";
		var insertIndex = exeSQL.execSQL(sql, exeSQL.TYPE_ARRAY)[0][0];
		riskTableUI.insertRowAfter(riskNameRowIndex + insertIndex, createPropertiesRow(riskScreenDatas[i], riskInfo.riskBaseItems[riskCode], true));
		riskScreenState[riskCode][riskScreenDatas[i]['ctrltype']] = true;
	}
}

/**
 * 类似于隐藏列，直接删除该列
 * @param riskCode 险种代码
 * @param riskScreenDatas 需要插入的列的参数 Array类型
 * PS:可能存在问题（riskScreenDatas与riskTableUI中顺序必须一致）
 * 删除多个Rows的时候可能出现问题！！！
 * */
function hiddenRows(riskCode, riskScreenDatas) {
	var tempIndex = 0;
	if (riskCode == riskInfo.mainRiskCode) {
		var mSection = riskTableUI.data[0];
		for (var i = 0; i < mSection.rowCount; i++) {
			if (mSection.rows[i].firstTag == riskScreenDatas[tempIndex]['ctrltype']) {
				if (riskScreenState[riskCode][riskScreenDatas[tempIndex]['ctrltype']]) {
					riskTableUI.deleteRow(i);
					riskScreenState[riskCode][riskScreenDatas[tempIndex]['ctrltype']] = false;
					i--;
				}
				tempIndex++;
			}
			if (tempIndex >= riskScreenDatas.length) {
				break;
			}
		}
	} else {
		var sSection = riskTableUI.data[1];
		for (var i = 0; i < sSection.rowCount; i++) {
			if (tempIndex >= riskScreenDatas.length) {
				break;
			}

			if (sSection.rows[i].firstTag == riskScreenDatas[tempIndex]['ctrltype']) {
				if (riskScreenState[riskCode][riskScreenDatas[tempIndex]['ctrltype']]) {
					riskTableUI.deleteRow(riskTableUI.data[0].rowCount + i);
					riskScreenState[riskCode][riskScreenDatas[tempIndex]['ctrltype']] = false;
					tempIndex++;
				}

			}
		}
	}

}

/**
 * 删除指定附加险RiskCode的所有条目
 * @param riskCode 险种代码
 *
 * */
function hiddenAllRows(riskCode) {
	//主险跳过
	if (riskCode == riskInfo.mainRiskCode) {
		return;
	}
	var mSection = riskTableUI.data[0];
	var sSection = riskTableUI.data[1];
	var startIndex = -1;
	var endIndex = -1;
	for (var i = 0; i < sSection.rowCount; i++) {
		//记录险种开始的标记
		if (sSection.rows[i].firstTag == 'RiskCode' && sSection.rows[i].secordTag == riskCode) {
			startIndex = i;
		}

		//该险种最后的标记
		if (sSection.rows[i].firstTag == 'RiskCode' && sSection.rows[i].secordTag != riskCode && endIndex == -1 && startIndex != -1) {
			endIndex = i;
		}
	}

	//最后一个险种的时候关闭所有
	if (endIndex == -1) {
		endIndex = sSection.rowCount;
	}

	Ti.API.warn('[RiskTable]关闭险种起始索引:' + startIndex);
	Ti.API.warn('[RiskTable]关闭险种结束索引:' + endIndex);

	for (var i = endIndex - 1; i > startIndex; i--) {
		var deleteIndex = i + mSection.rowCount;
		Ti.API.warn('删除Row的索引为:' + deleteIndex);
		riskTableUI.deleteRow(deleteIndex);
	}

	riskScreenState[riskCode] = new Object();

}

/**
 * 改变列的值域
 * 限定与一条Row
 * @param riskCode 险种代码
 * @param ctrlCode 变化的Row标记
 * @param defualtSQL 根据变化的sql
 * */
function changeRow(riskCode, ctrlCode, defualtSQL) {

	var section = riskTableUI.data[0];
	if (riskCode != riskInfo.mainRiskCode) {
		section = riskTableUI.data[1];
	}

	var tempRiskCode = '';
	for (var i = 0; i < section.rowCount; i++) {
		if (section.rows[i].firstTag == 'RiskCode') {
			tempRiskCode = section.rows[i].secordTag;
		}
		if (tempRiskCode != riskCode) {
			continue;
		}
		if (section.rows[i].firstTag == ctrlCode) {
			var resultLabel = section.rows[i].children[1];
			resultLabel.secorndTag = defualtSQL;
			var resultSet = riskInfoHandler.CalSQLValue(defualtSQL, riskInfo.riskBaseItems[riskCode]);
			resultLabel.thirdTag = resultSet;
			var result = resultLabel.firstTag;
			var hasResult = false;
			for (var j = 0; j < resultSet.length; j++) {
				if (resultSet[j].value == result) {
					hasResult = true;
				}
			}
			if (!hasResult) {
				resultLabel.setText('');
				resultLabel.firstTag = '';
			}
		}
	}
}

/**
 * 展示万能险数据
 * */
//TODO
function showUniData(riskCode, standByFlag3, showWedget) {
	var marks = {}
	var typeSQL = "Select CtrlType From LMUniversalRiskScreen Where RiskCode = '" + riskCode + "' Group By CtrlType";
	var typeArry = exeSQL.execSQL(typeSQL, exeSQL.TYPE_ARRAY);
	//开始生成界面
	for (var i = 0; i < typeArry.length; i++) {
		var universalType = typeArry[i][0];
		//查找类型标记
		var LMUniversalRiskScreenDB = new dB('LMUniversalRiskScreen');
		LMUniversalRiskScreenDB['riskcode'] = this.riskCode;
		LMUniversalRiskScreenDB['ctrltype'] = universalType;
		var LMUniversalRiskScreenSet = LMUniversalRiskScreenDB.query();
		var markObject = {};
		for (var m = 0; m < LMUniversalRiskScreenSet.length; m++) {
			var tempSchema = LMUniversalRiskScreenSet[m];
			markObject[tempSchema['ctrlcode']] = tempSchema['ctrlname'];
		}
		marks[universalType] = markObject;
	}

	var tableData = [];

	for (var type in marks) {
		var InvestRiskDataDB = new dB('InvestRiskData');
		InvestRiskDataDB['signno'] = standByFlag3;
		InvestRiskDataDB['type'] = type;
		var InvestRiskDataSet = InvestRiskDataDB.query();
		for (var i = 0; i < InvestRiskDataSet.length; i++) {
			var InvestRiskDataSchema = InvestRiskDataSet[i];
			var titleStr = '';
			titleStr += (marks[type]['age'] + ': ' + InvestRiskDataSchema['age'] + '  ');
			titleStr += (marks[type]['degree'] + ': ' + InvestRiskDataSchema['degree'] + '  ');
			titleStr += (marks[type]['value'] + ': ' + InvestRiskDataSchema['value'] + '  ');
			tableData.push({
				title : titleStr
			});
		}
	}

	if (tableData.length == 0) {
		tableData.push({
			title : '不存在万能险数据，请添加'
		});
	}

	var popover = Ti.UI.iPad.createPopover({
		width : 500,
		height : 180,
		title : '万能险数据',
		barColor : '#ffffff',
		arrowDirection : 1
	});

	var tableView = Ti.UI.createTableView({
		data : tableData,
		top : 0,
		height : 180
	});
	popover.add(tableView);

	popover.show({
		view : showWedget,
		animated : true,
	});
}

///////////////////////////////界面结束/////////////////////////////////